// pages/car/car.js
Page({

  data: {
    carList: [],
    totalNum: 0,
    allPrice: 0
  },
  
  onLoad: function (options) {
    this.getcarList()
    this.addTotalNum()
  },
  
  onShow: function () {
   this.getcarList()
   this.addTotalNum()
  },

  getcarList(){
    let carList = getApp().globalData.carList
    this.setData({
      carList
    })
  },

  decrementNum(ev){
    let item = ev.currentTarget.dataset.item
    let arr = this.data.carList
    arr.find( (obj,index) => {
      if(obj.good_id == item.good_id && obj.num > 0 ){
        obj.num --;
        arr[index] = obj;
        this.setData({
          carList: arr
        })
        let totalNum = 0
        let allPrice = 0
        if(arr){
          arr.forEach(item => {
            totalNum += item.num
            allPrice += item.good_price*item.num
          })
          this.setData({
            totalNum,
            allPrice
          })
        }
      }
    })
  },
  incrementNum(ev){
    let item = ev.currentTarget.dataset.item
    let arr = this.data.carList
    arr.find( (obj,index) => {
      if(obj.good_id == item.good_id ){
        obj.num ++;
        arr[index] = obj;
        this.setData({
          carList: arr
        })
        let totalNum = 0
        let allPrice = 0
        if(arr){
          arr.forEach(item => {
            totalNum += item.num
            allPrice += item.good_price*item.num
          })
          this.setData({
            totalNum,
            allPrice
          })
        }
      }
    })
  },
  addTotalNum(){
    let itemList = getApp().globalData.carList
    let totalNum = 0
    let allPrice = 0
    if(itemList){
      itemList.forEach(item => {
        totalNum += item.num
        allPrice += item.good_price*item.num
      })
      this.setData({
        totalNum,
        allPrice
      })
    }
  },

  toPray(){
    if(getApp().isLog()){  //用户以及授权过，可以进行支付
      console.log('已经授权了，可以进行支付交易')
    }else{   //用户没有授权过，跳转到授权页面
      wx.showToast({
        title: '授权登录后方可支付哦！！',
        icon: "none"
      })
      setTimeout( () => {
        wx.navigateTo({
          url: '/pages/log/log',
        })
      },2000)
    }
  },

  isRemovegoods(ev){
    const idx = ev.currentTarget.dataset.idx
    const carList = this.data.carList
    carList.splice(idx,1)
    this.setData({
      carList
    })
    this.addTotalNum()
    getApp().globalData.carList = carList
  }

})